package http.secure.common.util;

import org.dromara.hutool.core.codec.binary.HexUtil;
import org.dromara.hutool.crypto.KeyUtil;
import org.dromara.hutool.crypto.Mode;
import org.dromara.hutool.crypto.Padding;
import org.dromara.hutool.crypto.asymmetric.KeyType;
import org.dromara.hutool.crypto.asymmetric.SM2;
import org.dromara.hutool.crypto.digest.SM3;
import org.dromara.hutool.crypto.symmetric.SM4;

public class SMHelper {
    public static String[] genSm2Keys() {
        SM2 sm2 = new SM2();
        return new String[]{HexUtil.encodeStr(sm2.getQ(false)), sm2.getDHex()};
    }

    public static String genSm4Key() {
        return HexUtil.encodeStr(KeyUtil.generateKey("SM4").getEncoded());
    }

    public static String sm2Encrypt(String plaintext, String pubkey) {
        SM2 sm2 = new SM2(null, pubkey);
        return sm2.encryptHex(plaintext, KeyType.PublicKey);
    }

    public static String sm2Decrypt(String ciphertext, String prikey) {
        SM2 sm2 = new SM2(prikey, null);
        return sm2.decryptStr(ciphertext, KeyType.PrivateKey);
    }

    public static String sm3Hash(String plaintext) {
        return new SM3().digestHex(plaintext);
    }

    public static String sm4Encrypt(String plaintext, String key, String salt) {
        return new SM4(Mode.CBC, Padding.PKCS5Padding, HexUtil.decode(key), HexUtil.decode(salt)).encryptHex(plaintext);
    }

    public static String sm4Decrypt(String ciphertext, String key, String salt) {
        return new SM4(Mode.CBC, Padding.PKCS5Padding, HexUtil.decode(key), HexUtil.decode(salt)).decryptStr(ciphertext);
    }
}
